package com.qianseit.westore.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.qianseit.westore.AgentApplication;
import com.qianseit.westore.BaseDoFragment;
import com.qianseit.westore.Run;
import com.qianseit.westore.TwoGoodsAdapter;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;
import com.qianseit.westore.ui.CircleFlowIndicator;
import com.qianseit.westore.ui.FlowView;
import com.qianseit.westore.ui.PromotionCategoryView;
import com.qianseit.westore.ui.PromotionCategoryView.OnCategoryClickListener;
import com.qianseit.westore.ui.pulltorefresh.lib.PullToRefreshBase.OnRefreshListener;
import com.qianseit.westore.ui.pulltorefresh.lib.PullToRefreshListView;
import com.qianseit.westore.util.loader.VolleyImageLoader;
import com.beautymiracle.androidclient.R;

public class PromotionsFragment extends BaseDoFragment {

	private final static int INTERVAL_AUTO_SNAP_FLOWVIEW = 5000;

	private PromotionCategoryView mPromotionCategoryView;
	private FlowView mTopAdsView;

	private VolleyImageLoader mVolleyImageLoader;
	private Point mScreenSize;
	private TwoGoodsAdapter mAdapter;

	private PullToRefreshListView mListView;
	private View mAdsLayoutView;
	private int mCategoryIndex;

	private ArrayList<JSONObject> mTopAdsArray = new ArrayList<JSONObject>();
	private ArrayList<JSONObject> mGoodsArray = new ArrayList<JSONObject>();
	private ArrayList<String> mNameArray = new ArrayList<String>();
	private ArrayList<String> mIds = new ArrayList<String>();

	public PromotionsFragment() {
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mScreenSize = Run.getScreenSize(mActivity.getWindowManager());
		mVolleyImageLoader = ((AgentApplication) mActivity.getApplication())
				.getImageLoader();
	}

	@Override
	public void onResume() {
		super.onResume();
		mHandler.sendEmptyMessageDelayed(0, INTERVAL_AUTO_SNAP_FLOWVIEW);
	}

	@Override
	public void onPause() {
		super.onPause();
		mHandler.removeMessages(0);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActionBar.setTitle(R.string.tabbar_title3);
		mActionBar.setShowHomeView(false);

		rootView = inflater.inflate(R.layout.fragment_promotions, null);
		mPromotionCategoryView = (PromotionCategoryView) rootView
				.findViewById(R.id.fragment_promotion_category);
		mPromotionCategoryView.setCategoryOnclickListener(listener);

		mListView = (PullToRefreshListView) rootView
				.findViewById(R.id.fragment_promotion_listview);
		mAdsLayoutView = findViewById(R.id.fragment_promotion_adsview_layout);
		mTopAdsView = (FlowView) rootView
				.findViewById(R.id.fragment_promotion_adsview);
		Run.removeFromSuperView(mAdsLayoutView);
		mAdsLayoutView.setLayoutParams(new AbsListView.LayoutParams(
				mAdsLayoutView.getLayoutParams()));
		mListView.getRefreshableView().addHeaderView(mAdsLayoutView);
		mAdapter = new GoodsGridAdapter();
		mListView.getRefreshableView().setAdapter(mAdapter);

		mListView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				mListView.setRefreshing();
				new JsonTask().execute(new GetPromotionTask());
				new JsonTask().execute(new GetTopAds());
			}

			@Override
			public void onRefreshMore() {

			}
		});

		// 加载数据
		mListView.setRefreshing();
		new JsonTask().execute(new GetPromotionTask());
		new JsonTask().execute(new GetTopAds());
	}

	private void reloadAdsView() {
		if (mTopAdsArray != null && mTopAdsArray.size() > 0) {
			CircleFlowIndicator mTopAdsIndicator = (CircleFlowIndicator) rootView
					.findViewById(R.id.fragment_promotion_adsview_indicator);
			mTopAdsIndicator.setVisibility(View.VISIBLE);
			mTopAdsView.setAdapter(new FlowAdapter());
			mTopAdsView.setFlowIndicator(mTopAdsIndicator);
			mTopAdsIndicator.setViewFlow(mTopAdsView);
			try {
				JSONObject topAdsObject = mTopAdsArray.get(0);

				// 根据屏幕和图片大小调整显示尺寸
				int width = topAdsObject.optInt("ad_img_w");
				int height = topAdsObject.optInt("ad_img_h");
				int viewHeight = mScreenSize.x * height / width;
				LayoutParams params = mTopAdsView.getLayoutParams();
				params.height = viewHeight;
				mTopAdsView.setLayoutParams(params);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			rootView.findViewById(R.id.fragment_promotion_adsview_indicator)
					.setVisibility(View.GONE);
		}
	}

	private class GetPromotionTask implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			mListView.onRefreshComplete();

			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONArray list = all.getJSONArray("data");
					int size = (list == null) ? 0 : list.length();
					mNameArray.clear();
					mIds.clear();
					for (int i = 0; i < size; i++) {
						JSONObject obj = list.getJSONObject(i);
						mNameArray.add(obj.optString("name"));
						JSONObject conditions = obj.optJSONObject("conditions");
						mIds.add(conditions.optString("goods_select"));
					}
					JSONObject good = list.getJSONObject(0);
					JSONArray data = good.getJSONArray("goods");
					parserGoods(data);
					mPromotionCategoryView.setCategory(mNameArray,true);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			JsonRequestBean req = new JsonRequestBean(Run.API_URL,
					"mobileapi.salesgoods.sales_list");
			return req;
		}

	}

	private class GetGoodsByIds implements JsonTaskHandler {

		private String ids;

		private GetGoodsByIds(String ids) {
			this.ids = ids;
		}

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONArray list = all.getJSONArray("data");
					parserGoods(list);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			showLoadingDialog();
			JsonRequestBean req = new JsonRequestBean(Run.API_URL,
					"mobileapi.salesgoods.get_sales_goods");
			req.addParams("ids", ids);
			return req;
		}

	}

	private class GetTopAds implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				mTopAdsArray.clear();
				if (Run.checkRequestJson(mActivity, all)) {
					JSONArray list = all.getJSONArray("data");
					list = list.getJSONObject(0).getJSONArray("items");
					int count = (list != null) ? list.length() : 0;
					for (int i = 0; i < count; i++) {
						mTopAdsArray.add((JSONObject) list.get(i));
					}
					reloadAdsView();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			return new JsonRequestBean(Run.API_URL,
					"mobileapi.salesgoods.get_sales_ads").addParams(
					"ad_type", "common").addParams("ad_type_id", "comm_ad");
		}

	}

	private void parserGoods(JSONArray jsonArray) {
		int size = jsonArray == null ? 0 : jsonArray.length();
		mGoodsArray.clear();
		for (int i = 0; i < size; i++) {
			try {
				mGoodsArray.add(jsonArray.getJSONObject(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
			mListView.getRefreshableView().setSelection(0);
		}
	}

	private OnCategoryClickListener listener = new OnCategoryClickListener() {

		@Override
		public void onClick(View view, int position) {
			mCategoryIndex = position;
			new JsonTask().execute(new GetGoodsByIds(mIds.get(mCategoryIndex)));
		}
	};

	private OnClickListener mAdViewClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (v.getTag(R.id.tag_object) != null) {
				JSONObject data = (JSONObject) v.getTag(R.id.tag_object);
				String urlType = data.optString("url_type");
				if ("goods".equals(urlType)) {
					startActivity(AgentActivity.intentForFragment(mActivity,
							AgentActivity.FRAGMENT_GOODS_DETAIL).putExtra(
							Run.EXTRA_CLASS_ID, data.optString("ad_url")));
				} else if ("article".equals(urlType)) {
					startActivity(AgentActivity.intentForFragment(mActivity,
							AgentActivity.FRAGMENT_ARTICLE_READER).putExtra(
							Run.EXTRA_ARTICLE_ID, data.optString("ad_url")));
				} else if ("virtual_cat".equals(urlType)) {
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_LIST)
							.putExtra(Run.EXTRA_VITUAL_CATE,
									data.optString("ad_url"))
							.putExtra(Run.EXTRA_TITLE,
									data.optString("ad_name")));
				} else if ("cat".equals(urlType)) {
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_LIST)
							.putExtra(Run.EXTRA_CLASS_ID,
									data.optString("ad_url"))
							.putExtra(Run.EXTRA_TITLE,
									data.optString("ad_name")));
				}
			}
		}
	};

	private class FlowAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mTopAdsArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mTopAdsArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				ImageView view = new ImageView(mActivity);
				view.setLayoutParams(new AbsListView.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
				view.setScaleType(ScaleType.CENTER_CROP);
				view.setOnClickListener(mAdViewClickListener);
				convertView = view;
			}

			JSONObject topAdsObject = getItem(position);
			convertView.setTag(R.id.tag_object, topAdsObject);
			mVolleyImageLoader.showImage((ImageView) convertView,
					topAdsObject.optString("ad_img"));
			return convertView;
		}

	}

	private class GoodsGridAdapter extends TwoGoodsAdapter {

		public GoodsGridAdapter() {
			super(PromotionsFragment.this.mActivity,
					PromotionsFragment.this.mVolleyImageLoader,
					PromotionsFragment.this.mGoodsArray);
		}

		@Override
		public void onClick(View v) {
			if (v.getTag() != null && !TextUtils.isEmpty((String) v.getTag()))
				openGoodsDetailPage((String) v.getTag());
		}

		public void fillupItemView(View convertView, JSONObject all, String key) {
			PromotionsFragment.this.fillupItemView(convertView, all, key);
		}

	}

	private void openGoodsDetailPage(String goodsIID) {
		Intent intent = AgentActivity.intentForFragment(mActivity,
				AgentActivity.FRAGMENT_GOODS_DETAIL).putExtra(
				Run.EXTRA_CLASS_ID, goodsIID);
		mActivity.startActivity(intent);
	}

	private void fillupItemView(View convertView, JSONObject all, String key) {
		convertView.setBackgroundResource(R.drawable.card_background);

		int paddingSmall = mActivity.getResources().getDimensionPixelSize(
				R.dimen.PaddingSmall);
		TextView titleView = (TextView) convertView
				.findViewById(android.R.id.title);
		titleView.setSingleLine(false);
		titleView.setLines(2);
		titleView.setText(all.optString("title"));
		titleView.setPadding(paddingSmall, 0, paddingSmall, 0);

		// 购买说明
		View summary = convertView.findViewById(android.R.id.summary);
		summary.setVisibility(View.GONE);

		((TextView) convertView.findViewById(android.R.id.text1)).setText(Run
				.buildString("￥", all.optString("price")));
		TextView tv2 = (TextView) convertView.findViewById(android.R.id.text2);
		tv2.setText(Run.buildString("￥", all.optString("market_price")));
		tv2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

		try {
			ImageView iconView = (ImageView) convertView
					.findViewById(android.R.id.icon);
			String imageUrl = "";
			JSONArray item_imgs = all.optJSONArray("item_imgs");
			if (item_imgs != null && item_imgs.length() > 0) {
				JSONObject imgs = item_imgs.optJSONObject(0);
				if (imgs != null)
					imageUrl = imgs.optString("thisuasm_url");
			}
			if (TextUtils.isEmpty(imageUrl))
				imageUrl = all.optString("default_img_url");
			iconView.setImageBitmap(null);
			mVolleyImageLoader.showImage(iconView, imageUrl);

			((FrameLayout) iconView.getParent()).setForeground(null);
		} catch (Exception e) {
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (mTopAdsView.getViewsCount() > 1) {
				int count = mTopAdsView.getViewsCount();
				int curScreen = mTopAdsView.getSelectedItemPosition();
				if (curScreen >= (count - 1))
					mTopAdsView.smoothScrollToScreen(0);
				else
					mTopAdsView.smoothScrollToScreen(curScreen + 1);
			}
			mHandler.sendEmptyMessageDelayed(0, INTERVAL_AUTO_SNAP_FLOWVIEW);
		};
	};

}
